import router from './index'
import { useInfoStore } from '@/stores/user'
import axios from 'axios'

router.beforeEach(async (to, from, next) => {
  
  const { token } = useInfoStore()
  if (token) {
    if (to.path === '/login') {
      next('/')
    }
    if (router.getRoutes().length === 3) {
      const res = await axios.post('/getPermissions', {token})
      let permissionsList = res.data.permissions
      permissionsList.forEach(item => {
        router.addRoute('Layout', {
          path: item.path,
          name: item.name,
          component: () => import(`@/views/${item.path}/index.vue`),
          meta:item.meta
        })
      })
     next({ ...to, replace: true })
    }else {
      next()
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})